﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using Telerik.Web.UI;
using System.Collections.Specialized;
using System.Data;
using SalePartial.Utility;
using XunPan.Web.Globals;
using System.Text.RegularExpressions;
using SalePartial.BLL;
using SalePartial.Model;

public partial class Trade_Resource_vendor_retrieval : System.Web.UI.Page
{
    protected void Page_Load(object sender, System.EventArgs e)
    {
        if (!IsPostBack)
        {
            LoadAllLocationNodes(rtvLocation);
            sdsVendorList.FilterParameters["Filter1"].DefaultValue = "";
        }
       
    }

    //**************************************************************************************************************************8
    //此代码将加载用户自定义的检索条件至下拉菜单

    //**************************************************************************************************************************8

    private void LoadVendorFoldersTree()
    {

        if (Context.Profile.IsAnonymous)
        {
            //to add redirect page here, as the user is anonymous or the user is not authorized
            GlobalUtility.ForceLogin();

            return;
        }


        //读取对应属性的配置
        //Load Property
        string folderXML = Context.Profile.GetPropertyValue("VendorTreeFromBuyer").ToString();
        if (folderXML.Equals(""))
        {
            //用户没有设置该属性
            //if (rtvMyVendors.Nodes.Count == 1 && rtvMyVendors.Nodes[0].Nodes.Count == 0)
            //{
            //    RadTreeNode defaultFolder = new RadTreeNode("我的供应商库 1 (0)", Guid.NewGuid().ToString());
            //    defaultFolder.ImageUrl = rtvMyVendors.Nodes[0].ImageUrl;
            //    rtvMyVendors.Nodes[0].Nodes.Add(defaultFolder);
            //}

        }
        //else
        //{
        //    // clear all nodes
        //    rtvMyVendors.Nodes.Clear();
        //    //加载用户文件夹
        //    rtvMyVendors.LoadXml(folderXML);

        //}

        //UpdateVendorFolder();


    }

    /// <summary>
    /// 更新收藏夹的下拉菜单列表
    /// </summary>
    /// <remarks></remarks>
    //private void UpdateVendorFolder()
    //{
    //    rcbVendorFolders.Items.Clear();
    //    foreach (RadTreeNode tnode in rtvMyVendors.GetAllNodes())
    //    {
    //        if (tnode.Nodes.Count == 0)
    //        {
    //            rcbVendorFolders.Items.Add(new RadComboBoxItem(tnode.Text, tnode.Value));
    //        }
    //    }
    //}

    //**************************************************************************************************************************8
    //此部分代码将动态加载省市树状目录的加载
    //**************************************************************************************************************************8


    private static void LoadRootNodes(RadTreeView treeView, TreeNodeExpandMode expandMode)
    {
        DataSet data = new DataSet();
        data.ReadXml(HttpContext.Current.Server.MapPath("~/App_Data/XML/China_Provinces.xml"));


        foreach (DataRow row in data.Tables[0].Rows)
        {
            RadTreeNode node = new RadTreeNode();
            node.Text = row["ProvinceName"].ToString();
            node.Value = row["ID"].ToString();
            node.ExpandMode = expandMode;
            treeView.Nodes.Add(node);
        }

    }

    private static void LoadAllLocationNodes(RadTreeView treeView)
    {
        DataSet data = new DataSet();
        data.ReadXml(HttpContext.Current.Server.MapPath("~/App_Data/XML/China_Provinces.xml"));


        foreach (DataRow row in data.Tables[0].Rows)
        {
            RadTreeNode provincenode = new RadTreeNode();
            provincenode.Text = row["ProvinceName"].ToString();
            provincenode.Value = row["ID"].ToString();


            DataTable dt = GetCitiesData(provincenode.Value);

            foreach (DataRow dr in dt.Rows)
            {
                RadTreeNode citynode = new RadTreeNode();
                citynode.Text = dr["CityName"].ToString();
                citynode.Value = dr["ID"].ToString();
                provincenode.Nodes.Add(citynode);
            }

            treeView.Nodes.Add(provincenode);
        }


    }

    private static DataTable GetCitiesData(string pid)
    {
        DataSet data = new DataSet();
        data.ReadXml(HttpContext.Current.Server.MapPath("~/App_Data/XML/China_Cities.xml"));

        DataView dv = new DataView(data.Tables[0]);
        //dv.Sort = "CityName ASC"
        dv.RowFilter = "[PID] = '" + pid + "'";
        return dv.ToTable();

    }
    private static void PopulateNodeOnDemand(RadTreeNodeEventArgs e, TreeNodeExpandMode expandMode)
    {
        DataTable data = GetCitiesData(e.Node.Value);

        foreach (DataRow row in data.Rows)
        {
            RadTreeNode node = new RadTreeNode();
            node.Text = row["CityName"].ToString();
            node.Value = row["ID"].ToString();
            e.Node.Nodes.Add(node);
        }

        e.Node.Expanded = true;
    }

    protected void rtvLocation_NodeExpand(object sender, Telerik.Web.UI.RadTreeNodeEventArgs e)
    {
        PopulateNodeOnDemand(e, TreeNodeExpandMode.ServerSideCallBack);
        //PopulateNodeOnDemand(e, TreeNodeExpandMode.ServerSide)

    }

    protected void rtvMyVendors_ContextMenuItemClick(object sender, Telerik.Web.UI.RadTreeViewContextMenuEventArgs e)
    {
        RadTreeNode clickedNode = e.Node;
        string unreadPattern = "\\(\\d+\\)";

        switch (e.MenuItem.Value)
        {
            case "NewFolder":

                if (clickedNode.Nodes.Count < GlobalSetting.MaxVendorFolderQuantity)
                {
                    RadTreeNode newFolder = new RadTreeNode(string.Format("我的供应商库 {0} (0)", clickedNode.Nodes.Count + 1));
                    newFolder.Selected = true;
                    newFolder.ImageUrl = clickedNode.ImageUrl;
                    newFolder.Value = Guid.NewGuid().ToString();

                    clickedNode.Nodes.Add(newFolder);
                    clickedNode.Expanded = true;
                    //update the number in the brackets
                    if (Regex.IsMatch(clickedNode.Text, unreadPattern))
                    {
                        clickedNode.Text = Regex.Replace(clickedNode.Text, unreadPattern, "(" + clickedNode.Nodes.Count.ToString() + ")");
                    }
                    else
                    {
                        clickedNode.Text += string.Format(" ({0})", clickedNode.Nodes.Count);
                    }

                    //string folerXML = rtvMyVendors.GetXml();
                    //Context.Profile.SetPropertyValue("VendorTreeFromBuyer", folerXML);
                    //Context.Profile.Save();

                    //UpdateVendorFolder();


                    //clickedNode.Font.Bold = True
                    //'set node's value so we can find it in startNodeInEditMode
                    //newFolder.Value = newFolder.GetFullPath("/")
                    //startNodeInEditMode(newFolder.Value)
                    break; // TODO: might not be correct. Was : Exit Select
                }
                break;
            case "Delete":
                //'below code ensure the clicked node is not the only one child node of root
                //If clickedNode.ParentNode.ParentNode Is Nothing AndAlso clickedNode.ParentNode.Nodes.Count = 1 Then
                //    Exit Select
                //End If

                RadTreeNode parent = clickedNode.ParentNode;

                //update the number in the brackets of parent node's text
                if (Regex.IsMatch(parent.Text, unreadPattern))
                {
                    parent.Text = Regex.Replace(parent.Text, unreadPattern, "(" + parent.Nodes.Count.ToString() + ")");
                }
                else
                {
                    parent.Text += string.Format(" ({0})", parent.Nodes.Count);
                }

                clickedNode.Remove();

                //string folerXML2 = rtvMyVendors.GetXml();
                //Context.Profile.SetPropertyValue("VendorTreeFromBuyer", folerXML2);
                Context.Profile.Save();


                //UpdateVendorFolder();

                string fid = clickedNode.Value.ToString();
                string cid = sdsMyVendorList.SelectParameters["OwnerCompanyID"].DefaultValue;

                try
                {
                    XPFavoriteVedor favorVedor = new XPFavoriteVedor();
                    favorVedor.DeleteDynamic("CompanyID = '" + cid + "' AND FolderID = '" + fid + "'");


                }
                catch (Exception ex)
                {
                }

                break;

            default:

                break;
        }
    }

    //Private Sub startNodeInEditMode(ByVal nodeValue As String)
    //    'find the node by its Value and edit it when page loads
    //    Dim js As String = "Sys.Application.add_load(editNode); function editNode(){ "
    //    js += "var tree = $find(""" + RadTreeView1.ClientID + """);"
    //    js += "var node = tree.findNodeByValue('" + nodeValue + "');"
    //    js += "if (node) node.startEdit();"
    //    js += "Sys.Application.remove_load(editNode);};"

    //    RadScriptManager.RegisterStartupScript(Page, Page.[GetType](), "nodeEdit", js, True)
    //End Sub

    /// <summary>
    /// 从显示的收藏夹名称中获取该收藏夹下的供应商数目
    /// </summary>
    /// <param name="foldername"></param>
    /// <returns></returns>
    /// <remarks></remarks>
    private string GetVendorCountByName(string foldername)
    {
        string unreadPattern = "\\(\\d+\\)";

        string count = null;
        //update the number in the brackets

        //子节点
        count = Regex.Match(foldername, unreadPattern).Value;

        return count;

    }



    /// <summary>
    /// 显示选中收藏夹的供应商列表
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    /// <remarks></remarks>
    protected void rtvMyVendors_NodeClick(object sender, Telerik.Web.UI.RadTreeNodeEventArgs e)
    {
        if (e.Node.Level > 0)
        {
            string fid = e.Node.Value;
            sdsMyVendorList.FilterExpression = "[FolderID] = '" + fid + "'";

            radGridVendorlist.DataBind();
        }

    }


    /// <summary>
    /// 编辑收藏夹名称
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    /// <remarks></remarks>
    protected void rtvMyVendors_NodeEdit(object sender, Telerik.Web.UI.RadTreeNodeEditEventArgs e)
    {
        string unreadPattern = "\\(\\d+\\)";

        string count = null;
        //update the number in the brackets

        if (e.Node.Nodes.Count > 0)
        {
            count = "(" + e.Node.Nodes.Count + ")";

        }
        else
        {
            //子节点
            count = Regex.Match(e.Node.Text, unreadPattern).Value;
        }
        e.Node.Text = e.Text + " " + count;

        //string folderXML = rtvMyVendors.GetXml();
        //Context.Profile.SetPropertyValue("VendorTreeFromBuyer", folderXML);
        Context.Profile.Save();


    }


    //Protected Sub lbtBackup_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lbtBackup.Click

    //    If radGridVendorlist.SelectedItems.Count > 0 Then
    //        If rdVendorFolders.Closed Then
    //            rdVendorFolders.Closed = False
    //        End If

    //    End If

    //End Sub

    /// <summary>
    /// 将选中的供应商添加到对应的目录下
    /// 如有重复配对信息，则跳过
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    /// <remarks></remarks>
    protected void lbtBackup_Click(object sender, System.EventArgs e)
    {
        //string fid = rcbVendorFolders.SelectedItem.Value;

        XPFavoriteVedor favorVedor = new XPFavoriteVedor();
        //if (GlobalUtility.IsValidGuid(fid))
        //{
            if (radGridVendorlist.SelectedItems.Count > 0)
            {
                foreach (GridDataItem gdata in radGridVendorlist.SelectedItems)
                {
                    string vid = gdata.OwnerTableView.DataKeyValues[gdata.ItemIndex]["CompanyID"].ToString();
                    string cid = sdsMyVendorList.SelectParameters["OwnerCompanyID"].DefaultValue;

                    
                    DataSet ds = favorVedor.SelectDynamic("CompanyID = '" + cid + "' AND VendorID = '" + vid + "'", "");

                    if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                    {
                        //已添加该供应商
                    }
                    else
                    {
                        XPFavoriteVedorInfo xpfavorInfo = new XPFavoriteVedorInfo();
                        xpfavorInfo.VendorID = new Guid(vid);
                        xpfavorInfo.CompanyID = new Guid(cid);
                        //xpfavorInfo.FolderID = new Guid(fid);

                        XPFavoriteVedor xpfavor = new XPFavoriteVedor();
                        xpfavor.Insert(xpfavorInfo);

                    }

                }

                //RadTreeNode rnode = rtvMyVendors.FindNodeByValue(fid);
                string unreadPattern = "\\(\\d+\\)";

                //int count = favorVedor.SelectDynamic("FolderID = '" + fid + "'", "").Tables[0].Rows.Count;
                //update the number in the brackets

                //子节点
               // rnode.Text = Regex.Replace(rnode.Text, unreadPattern, "(" + count.ToString() + ")");


                //string folderXML = rtvMyVendors.GetXml();

                //folderXML = folderXML.Replace(" Visible=\"False\"", "");
                //Context.Profile.SetPropertyValue("VendorTreeFromBuyer", folderXML);
                Context.Profile.Save();

                LoadVendorFoldersTree();


            }

        
    }

    /// <summary>
    /// 针对选中的供应商发布询盘信息
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    /// <remarks></remarks>
    protected void lbtPublish_Click(object sender, System.EventArgs e)
    {

        if (radGridVendorlist.SelectedItems.Count > 0)
        {
            DataTable dtvendors = new DataTable();
            dtvendors.Columns.Add("CompanyID");
            dtvendors.Columns.Add("CompanyName");

            foreach (GridDataItem gdata in radGridVendorlist.SelectedItems)
            {
                string vid = gdata.OwnerTableView.DataKeyValues[gdata.ItemIndex]["CompanyID"].ToString();
                string vname = gdata.OwnerTableView.DataKeyValues[gdata.ItemIndex]["CompanyName"].ToString();

                DataRow dr = dtvendors.NewRow();
                dr[0] = vid;
                dr[1] = vname;
                dtvendors.Rows.Add(dr);
            }

            HttpContext.Current.Session["c_selectedVendors_dt"]= dtvendors;
            Response.Redirect("~/Trade/Purchase/PurchNewInquery.aspx", false);


        }
    }


    /// <summary>
    /// 从当前收藏目录下移除选中的供应商
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    /// <remarks></remarks>

    //protected void lbtRemove_Click(object sender, System.EventArgs e)
    //{


    //    if (radGridVendorlist.SelectedItems.Count > 0)
    //    {
    //        foreach (GridDataItem gdata in radGridVendorlist.SelectedItems)
    //        {
    //            string vid = gdata.OwnerTableView.DataKeyValues[gdata.ItemIndex]["CompanyID"].ToString();
    //            string cid = sdsMyVendorList.SelectParameters["OwnerCompanyID"].DefaultValue;

    //            try
    //            {
    //                XPFavoriteVedor favorVedor = new XPFavoriteVedor();
    //                favorVedor.DeleteDynamic("CompanyID = '" + cid + "' AND VendorID = '" + vid + "'");


    //            }
    //            catch (Exception ex)
    //            {
    //            }

    //        }

    //        for (int i = 0; i <= rtvMyVendors.GetAllNodes().Count - 1; i++)
    //        {
    //            RadTreeNode rnode = rtvMyVendors.GetAllNodes()[i];
    //            if (rnode.ParentNode != null)
    //            {
    //                string unreadPattern = "\\(\\d+\\)";
    //                XPFavoriteVedor favorVedor = new XPFavoriteVedor();
    //                int count = favorVedor.SelectDynamic("FolderID = '" + rnode.Value + "'", "").Tables[0].Rows.Count;
    //                //update the number in the brackets

    //                //子节点
    //                rnode.Text = Regex.Replace(rnode.Text, unreadPattern, "(" + count.ToString() + ")");
    //            }
    //        }
    //        string folderXML = rtvMyVendors.GetXml();

    //        folderXML = folderXML.Replace(" Visible=\"False\"", "");
    //        Context.Profile.SetPropertyValue("VendorTreeFromBuyer", folderXML);
    //        Context.Profile.Save();

    //        LoadVendorFoldersTree();

    //    }
    //    radGridVendorlist.Rebind();

    //}

    protected void btnSearch_Click(object sender, System.EventArgs e)
    {
        StringCollection fe = new StringCollection();



        if (rtvWCCatalog.CheckedNodes.Count > 0)
        {
            string field = (rtvWCCatalog.DataSourceID == xdsWareCubes.ID ? "Product" : "Technology");

            string warecubefilter = "";
            foreach (RadTreeNode rtNode in rtvWCCatalog.CheckedNodes)
            {
                if (!rtvWCCatalog.CheckedNodes.Contains(rtNode.ParentNode))
                {
                    warecubefilter += string.Format("([{0}] LIKE '%{1}%') OR ", field, rtNode.Value);
                }
            }
            warecubefilter = warecubefilter.Remove(warecubefilter.LastIndexOf(" OR "));
            fe.Add(warecubefilter);

        }

        if (rtvLocation.CheckedNodes.Count > 0)
        {
            string provinceFilter = "";
            string cityFilter = "";

            foreach (RadTreeNode rtNode in rtvLocation.CheckedNodes)
            {
                switch (rtNode.Level)
                {
                    case 0:
                        provinceFilter = provinceFilter + rtNode.Text + "','";
                        break;
                    case 1:
                        cityFilter = cityFilter + rtNode.Text + "','";
                        break;
                    case 2:

                        break;
                    default:

                        break;
                }
            }

            if (provinceFilter.EndsWith(",'"))
            {
                provinceFilter = "[Province] IN ('" + provinceFilter.Remove(provinceFilter.LastIndexOf(",'")) + ")";
                fe.Add(provinceFilter);
            }

            if (cityFilter.EndsWith(",'"))
            {
                cityFilter = "[City] IN ('" + cityFilter.Remove(cityFilter.LastIndexOf(",'")) + ")";
                fe.Add(cityFilter);
            }

        }


        if (!tbKeyword.Text.Equals(""))
        {
            fe.Add("[CompanyName] LIKE '%" + tbKeyword.Text + "%' OR [Description] LIKE '%" + tbKeyword.Text + "%'");
        }




        if (fe.Count > 0)
        {
            string fullExpression = "(";
            for (int i = 0; i <= fe.Count - 1; i++)
            {
                fullExpression = fullExpression + fe[i] + ") AND (";
            }
            fullExpression = fullExpression.Remove(fullExpression.LastIndexOf(" AND ("));
            if (string.IsNullOrEmpty(sdsVendorList.FilterParameters["Filter1"].DefaultValue))
            {
                sdsVendorList.FilterParameters["Filter1"].DefaultValue = fullExpression;
            }
            else
            {
                sdsVendorList.FilterParameters["Filter1"].DefaultValue += "( " + fullExpression + ")";
            }
        }
       

        radGridVendorlist.DataBind();
    }
    protected void btnClear_Click(object sender, System.EventArgs e)
    {
        sdsVendorList.FilterParameters["Filter1"].DefaultValue = "";
        tbKeyword.Text = "";
        rtvLocation.UncheckAllNodes();
        rtvLocation.UnselectAllNodes();


        rtvWCCatalog.UncheckAllNodes();
        rtvWCCatalog.UnselectAllNodes();


        radGridVendorlist.DataBind();

    }

    protected void rtsMenuBar_TabClick(object sender, Telerik.Web.UI.RadTabStripEventArgs e)
    {
        switch (e.Tab.Value)
        {
            case "Part":
               
                rdzNavigator.Visible = true;
               



                rtvLocation.UncheckAllNodes();
                rtvLocation.UnselectAllNodes();
                tbKeyword.Text = "";
                rtvWCCatalog.DataSourceID = xdsWareCubes.ID;


                radGridVendorlist.DataSourceID = "sdsVendorList";
                break;
            case "Process":
                //bind process data to treeview
                
                rdzNavigator.Visible = true;
               


                rtvLocation.UncheckAllNodes();
                rtvLocation.UnselectAllNodes();
                tbKeyword.Text = "";
                rtvWCCatalog.DataSourceID = xdsProcess.ID;

                radGridVendorlist.DataSourceID = "sdsVendorList";
                break;
            case "MyVendors":
               
                rdzNavigator.Visible = false;
               


               

                radGridVendorlist.DataSourceID = "sdsMyVendorList";
                break;
        }
    }

    protected void radGridVendorlist_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
    {
        switch (e.CommandName.ToLower())
        {
            case "warecube":

                break;
            case "message":

                break;
            default:

                break;
        }
    }



}